//
//  TDBindBankCardViewController.m
//  TFB
//
//  Created by Nothing on 15/4/13.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "TDBindBankCardViewController.h"
#import "TSLocateView.h"
#import "TDBankSearchViewController.h"

#define FRONTIMAGEVIEW_TAG  100
#define BACKIMAGEVIEW_TAG   101
#define PROVINCEVIEW_TAG    102
#define CITYVIEW_TAG        103

@interface TDBindBankCardViewController ()
{
    NSInteger _takeImgTag;
    
    NSString *_sendFrontImage;
    NSString *_sendBackImage;
    TSLocateView * _loactionView;
    UIActionSheet * _sheet;
    TDBankNameInfo * _info;
    
    
}
@property (nonatomic, strong) NSArray * citiyArr;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;

@property (nonatomic, strong) NSArray * bankNameListArr;
@end


@implementation TDBindBankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([UIScreen mainScreen].bounds.size.height<=480) {
        self.BGScrollView.contentSize=CGSizeMake(0, 600);
    }
    if (kBandingBankCard == _state) {
        self.title = @"绑定银行卡";
    
        _BGview.frame = CGRectMake(_BGview.frame.origin.x,
                                   _OldCardNumber.superview.frame.origin.y,
                                   _BGview.frame.size.width,
                                   _BGview.frame.size.height);
        
        _OldCardNumber.superview.hidden = YES;
    }else if (kModificationBankCard == _state){
        self.title = @"修改银行卡信息";
        [self requestBankCardInfo];
        _OldCardNumber.superview.layer.cornerRadius = 5.0F;
        [_commitBtn setTitle:@"确认修改" forState:0];
    }else if (kbangDingXinYongCard == _state)
    {
        self.title = @"绑定银行卡";
        
        _BGview.frame = CGRectMake(_BGview.frame.origin.x,
                                   _OldCardNumber.superview.frame.origin.y,
                                   _BGview.frame.size.width,
                                   _BGview.frame.size.height);
        
        _OldCardNumber.superview.hidden = YES;
    }else if (kupXinYongCard == _state)
    {
        self.title = @"修改银行卡信息";
        [self requestBankCardInfo];
        _OldCardNumber.superview.layer.cornerRadius = 5.0F;
        [_commitBtn setTitle:@"确认修改" forState:0];
    }
    
    //[self backButton];
    [self creatLayerWithView:_cardNumTF.superview];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    [self creatUI];
     self.automaticallyAdjustsScrollViewInsets = NO;
    if ([[NSUserDefaults standardUserDefaults]objectForKey:CITIYLIST]) {
        
        self.citiyArr = [TDProvince userDefaultObjectWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:CITIYLIST]];
    }else{
        
        __weak typeof(self) weakSelf = self;
        [TDHttpEngine requestForGetProvinceWithCustId:[TDUser defaultUser].custId custMobile:[TDUser defaultUser].custLogin complete:^(BOOL succeed, NSString *msg, NSString *cod, NSArray *array) {
            
            weakSelf.citiyArr = array;
        }];
    }
}

-(void)requestBankCardInfo{
    
    //查询银行卡
    __weak typeof(self)weakSelf = self;
    [TDHttpEngine requestForGetBankCardInfoWithMobile:[TDUser defaultUser].custLogin WithCustId:[TDUser defaultUser].custId complete:^(BOOL succeed, NSString *msg, NSString *cod, NSArray *temArray) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (succeed) {
            
            if (temArray.count) {
                TDBankCardInfo * BankCardInfo = [temArray firstObject];
                _OldCardNumber.text  =   BankCardInfo.cardNo;
            }else{
                [weakSelf.view makeToast:msg duration:2.0f position:@"center"];
            }
        }
        else
        {
            [weakSelf.view makeToast:msg duration:2.0f position:@"center"];
            
        }
    }];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)creatUI
{
    self.cardFrontImageView.userInteractionEnabled = YES;
    self.cardFrontImageView.tag = FRONTIMAGEVIEW_TAG;
    UITapGestureRecognizer *frontTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(takePhoto:)];
    frontTap.numberOfTapsRequired = 1;
    frontTap.numberOfTouchesRequired = 1;
    frontTap.delegate = self;
    [self.cardFrontImageView addGestureRecognizer:frontTap];
    
    self.cardBackImageView.userInteractionEnabled = YES;
    self.cardBackImageView.tag = BACKIMAGEVIEW_TAG;
    UITapGestureRecognizer *backTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(takePhoto:)];
    backTap.numberOfTapsRequired = 1;
    backTap.numberOfTouchesRequired = 1;
    backTap.delegate = self;
    [self.cardBackImageView addGestureRecognizer:backTap];
    
    if (kModificationBankCard == _state) {
 
        self.cardNumTF.text = self.bankCardInfo.cardNo;
        self.lineNumTF.text = self.bankCardInfo.issno;
        
    }
    
}


- (void)takePhoto:(UITapGestureRecognizer *)tapGesture
{
    _takeImgTag = [[tapGesture view] tag];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    else{
        [self.view makeToast:@"该设备没有摄像头" duration:2.0f position:@"center"];
        return;
    }
    
//    _sheet = [[UIActionSheet alloc]initWithTitle:@"获取图片方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相册" otherButtonTitles:@"拍照", nil];
//    [_sheet showInView:self.view];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//    NSLog(@"照片信息--%@", info);
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    CGSize imagesize = image.size;
    imagesize.height = 968;
    imagesize.width = 1296;
    NSData *imageData = UIImageJPEGRepresentation([self imageWithImage:image scaledToSize:imagesize], 0.1);
    
    switch (_takeImgTag) {
            
        case FRONTIMAGEVIEW_TAG:{
            [self.cardFrontImageView setImage:image];
            _sendFrontImage = [imageData base64EncodedString];
        }
            break;
        case BACKIMAGEVIEW_TAG:{
            [self.cardBackImageView setImage:image];
            _sendBackImage = [imageData base64EncodedString];
        }
            break;
            
        default:
            break;
    }
}

//重新绘制图片的尺寸
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)getArea:(UITapGestureRecognizer *)tapGesture
{
    
}

- (IBAction)commitBtnClick:(id)sender {
    
    
    if (_sendBackImage.length <= 0 || _sendFrontImage.length <= 0) {
        
        [self.view makeToast:@"请上传图片" duration:2.0f position:@"center"];
        return;
    }

    if (_loactionView.citieID.length <= 0 ||_loactionView.provinceID.length <= 0) {
        [self.view makeToast:@"请选择省/市" duration:2.0f position:@"center"];
        return;
    }
    if ([_bankNameButton.titleLabel.text hasPrefix:@"请"]) {
        [self.view makeToast:@"请选择银行名称" duration:2.0f position:@"center"];
        return;
    }
    if ([_zhiHangButton.titleLabel.text hasPrefix:@"请"]) {
        [self.view makeToast:@"请选择支行名称" duration:2.0f position:@"center"];
        return;
    }
    NSString * operType = @"";
    NSString * oldCard = @"";
    if (kBandingBankCard == _state) {
        operType = @"1";
        oldCard = _cardNumTF.text;
        if (_cardNumTF.text.length <= 0) {
            [self.view makeToast:@"请输入银行卡号" duration:2.0f position:@"center"];
            return;
        }
        [self creatYinHangKa:operType withOld:oldCard];
        
    }else if(kModificationBankCard == _state){
        if (_cardNumTF.text.length <= 0) {
            [self.view makeToast:@"请输入新银行卡号" duration:2.0f position:@"center"];
            return;
        }
        if (_OldCardNumber.text.length <= 0) {
            [self.view makeToast:@"请输入原银行卡号" duration:2.0f position:@"center"];
            return;
        }
        if ([_OldCardNumber.text isEqualToString:_cardNumTF.text]) {
            [self.view makeToast:@"原银行卡号与新银行卡号不能一致" duration:2.0f position:@"center"];
            return;
        }
        operType = @"2";
        oldCard = _OldCardNumber.text;
        [self creatYinHangKa:operType withOld:oldCard];
        
    }else if (kbangDingXinYongCard == _state)
    {
        operType = @"1";
        oldCard = _cardNumTF.text;
        if (_cardNumTF.text.length <= 0) {
            [self.view makeToast:@"请输入银行卡号" duration:2.0f position:@"center"];
            return;
        }
        [self creatXinYongKa:operType withOld:oldCard];
    }else if (kupXinYongCard == _state)
    {
        if (_cardNumTF.text.length <= 0) {
        [self.view makeToast:@"请输入新银行卡号" duration:2.0f position:@"center"];
        return;
        }
        if (_OldCardNumber.text.length <= 0) {
            [self.view makeToast:@"请输入原银行卡号" duration:2.0f position:@"center"];
            return;
        }
        if ([_OldCardNumber.text isEqualToString:_cardNumTF.text]) {
            [self.view makeToast:@"原银行卡号与新银行卡号不能一致" duration:2.0f position:@"center"];
            return;
        }
        operType = @"2";
        oldCard = _OldCardNumber.text;
        [self creatXinYongKa:operType withOld:oldCard];
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [TDHttpEngine requestForUpBankCardWithCustId:[TDUser defaultUser].custId custMobile:[TDUser defaultUser].custLogin OperType:operType oldCardNo:oldCard cardNo:self.cardNumTF.text cardFront:_sendFrontImage cardBack:_sendBackImage provinceId:_loactionView.provinceID cityId:_loactionView.citieID cnapsCode:_info.cnapsCode complete:^(BOOL succeed, NSString *msg, NSString *cod) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view makeToast:msg duration:2.0f position:@"center"];
        if (succeed) {
            [self performSelector:@selector(popToRoot) withObject:self afterDelay:2.5f];
        }
        else{
            
        }
    }];
}
-(void)creatXinYongKa:(NSString *)operType withOld:(NSString*)oldCard
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [TDHttpEngine requestForUpXingYongKaBankCardWithCustId:[TDUser defaultUser].custId custMobile:[TDUser defaultUser].custLogin OperType:operType oldCardNo:oldCard cardNo:self.cardNumTF.text cardFront:_sendFrontImage cardBack:_sendBackImage provinceId:_loactionView.provinceID cityId:_loactionView.citieID cnapsCode:_info.cnapsCode complete:^(BOOL succeed, NSString *msg, NSString *cod) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view makeToast:msg duration:2.0f position:@"center"];
        if (succeed) {
            [self performSelector:@selector(popToRoot) withObject:self afterDelay:2.5f];
        }
        else{
            
        }
    }];
}
-(void)creatYinHangKa:(NSString *)operType withOld:(NSString*)oldCard
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [TDHttpEngine requestForUpBankCardWithCustId:[TDUser defaultUser].custId custMobile:[TDUser defaultUser].custLogin OperType:operType oldCardNo:oldCard cardNo:self.cardNumTF.text cardFront:_sendFrontImage cardBack:_sendBackImage provinceId:_loactionView.provinceID cityId:_loactionView.citieID cnapsCode:_info.cnapsCode complete:^(BOOL succeed, NSString *msg, NSString *cod) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view makeToast:msg duration:2.0f position:@"center"];
        if (succeed) {
            [self performSelector:@selector(popToRoot) withObject:self afterDelay:2.5f];
        }
        else{
            
        }
    }];
}
- (void)popToRoot
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (IBAction)clickTRButton:(UIButton *)sender {
    
    if (sender == _TRButton) {
        [self.view endEditing:YES];
//        if (!self.BGScrollView.contentOffset.y) {
//            [self.BGScrollView setContentOffset:CGPointMake(0, 120) animated:YES];
//        }
        if (!_loactionView) {
            _loactionView  = [[TSLocateView alloc]initWithTitle:@"选择省/市" delegate:self];
            _loactionView.viewType = kCERVIEW;
            [_loactionView updataWithArray:self.citiyArr];
        }
        if (_loactionView.isCanShow) {
            [_loactionView showInView:self.view];
        }
        
        _lineNumImageV.highlighted = NO;
        _AreaImageV.highlighted = YES;
        _zhiHangImageV.highlighted = NO;
        
    }else if (sender == _bankNameButton){
     
        if (_loactionView.citieID.length <= 0 ||_loactionView.provinceID.length <= 0) {
            [self.view makeToast:@"请选择省/市" duration:2.0f position:@"center"];
            return;
        }
        
        [self RequestBankName];

        _lineNumImageV.highlighted = YES;
        _AreaImageV.highlighted = NO;
        _zhiHangImageV.highlighted = NO;
    }else if (sender == _zhiHangButton){
       
        if (_loactionView.citieID.length <= 0 ||_loactionView.provinceID.length <= 0) {
            [self.view makeToast:@"请选择省/市" duration:2.0f position:@"center"];
            return;
        }
        if ([_bankNameButton.titleLabel.text hasPrefix:@"请"]) {
            [self.view makeToast:@"请选择银行名称" duration:2.0f position:@"center"];
            return;
        }
        [self RequestBankListName];
        
        _lineNumImageV.highlighted = NO;
        _AreaImageV.highlighted = NO;
        _zhiHangImageV.highlighted = YES;
    }
    

    _bankNumImageV.highlighted = NO;

}
-(void)getBankNameInfo:(TDBankNameInfo *)info{
  
    [_zhiHangButton setTitle:info.subBranch forState:0];
    _info = info;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (_sheet == actionSheet) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        if (buttonIndex == 1) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;
            }
            else{
                [self.view makeToast:@"该设备没有摄像头" duration:2.0f position:@"center"];
                return;
            }
        }else if (buttonIndex == 0){
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
                imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
            }
        }
        [self presentViewController:imagePicker animated:YES completion:nil];
        return;
    }
    
    
    
    _bankNumImageV.highlighted = NO;
    _lineNumImageV.highlighted = NO;
    _AreaImageV.highlighted = NO;
    if (self.BGScrollView.contentOffset.y) {
        [self.BGScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    
    if(buttonIndex == 0) {
        
        
    }else {
        
        [_TRButton setTitle:[NSString stringWithFormat:@"%@ / %@",_loactionView.province,_loactionView.citie] forState:0];
        
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [_loactionView cancelWithView];

//        [self.BGScrollView setContentOffset:CGPointMake(0, 120) animated:YES];
    if (textField == _cardNumTF) {
        _bankNumImageV.highlighted = YES;
        _lineNumImageV.highlighted = NO;
        _AreaImageV.highlighted = NO;
    }else if (textField == _lineNumTF){
        _bankNumImageV.highlighted = NO;
        _lineNumImageV.highlighted = YES;
        _AreaImageV.highlighted = NO;
    }else if (textField == _OldCardNumber){
        _bankNumImageV.highlighted = NO;
        _lineNumImageV.highlighted = NO;
        _AreaImageV.highlighted = NO;
        _OldBankImageV.highlighted = YES;
    }
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
//    if (self.BGScrollView.contentOffset.y) {
//        [self.BGScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
//    }
    _bankNumImageV.highlighted = NO;
    _lineNumImageV.highlighted = NO;
    _AreaImageV.highlighted = NO;
    _zhiHangImageV.highlighted = NO;
    if (!_OldCardNumber.superview.hidden) {
        _OldBankImageV.highlighted = NO;
    }
    
    [textField resignFirstResponder];
    return YES;
}

-(void)clickbackButton{

    [self.navigationController popToRootViewControllerAnimated:YES];

}

-(void)RequestBankName{
   
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  [TDHttpEngine requestGetBankNameWithCustId:[TDUser defaultUser].custId custMobile:[TDUser defaultUser].custLogin bankProId:_loactionView.provinceID bankCityId:_loactionView.citieID complete:^(BOOL succeed, NSString *msg, NSString *cod, NSArray *bankList) {
      [MBProgressHUD hideHUDForView:self.view animated:YES];
      if (succeed) {
          _bankNameListArr = [NSArray arrayWithArray:bankList];
          ZSYPopoverListView *listView = [[ZSYPopoverListView alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
          listView.tag = 100;
          listView.titleName.text = @"请选择银行名称";
          listView.datasource = self;
          listView.delegate = self;
          
          [listView show];
          
          
      }else{
      [self.view makeToast:msg duration:2.0f position:@"center"];
      }
      
  }];
}
-(void)RequestBankListName{

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  [TDHttpEngine requestGetBankListNameCustId:[TDUser defaultUser].custId custMobile:[TDUser defaultUser].custLogin bankProId:_loactionView.provinceID bankCityId:_loactionView.citieID bankName:_bankNameButton.titleLabel.text complete:^(BOOL succeed, NSString *msg, NSString *cod, NSArray *bankList) {
     
      [MBProgressHUD hideHUDForView:self.view animated:YES];
      if (succeed) {
          TDBankSearchViewController * search = [[TDBankSearchViewController alloc]initWithNibName:@"TDBankSearchViewController" bundle:[NSBundle bundleWithPath:SRCBUNDLEPATH]];
          search.delegate = self;
          search.dataArray = [NSArray arrayWithArray:bankList];
          [self.navigationController pushViewController:search animated:YES];
      }else{
          [self.view makeToast:msg duration:2.0f position:@"center"];
      }
  }];

}

#pragma mark -
- (NSInteger)popoverListView:(ZSYPopoverListView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _bankNameListArr.count;
}

- (UITableViewCell *)popoverListView:(ZSYPopoverListView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusablePopoverCellWithIdentifier:identifier];
    if (nil == cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if ( self.selectedIndexPath && NSOrderedSame == [self.selectedIndexPath compare:indexPath])
    {
        cell.imageView.image = [UIImage imageNamed:@"fs_main_login_selected.png"];
    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:@"fs_main_login_normal.png"];
    }
    cell.textLabel.text = _bankNameListArr[indexPath.row];
    return cell;
}

- (void)popoverListView:(ZSYPopoverListView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView popoverCellForRowAtIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:@"fs_main_login_normal.png"];

}

- (void)popoverListView:(ZSYPopoverListView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndexPath = indexPath;
    UITableViewCell *cell = [tableView popoverCellForRowAtIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:@"fs_main_login_selected.png"];
    [_bankNameButton setTitle:_bankNameListArr[indexPath.row] forState:0];
    [tableView dismiss];
}

@end
